package com.infra.micro.oss.domain.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infra.common.resp.PageEx;
import com.infra.common.resp.Response;
import com.infra.common.util.BizUtils;
import com.infra.micro.oss.domain.db.entity.BizInfoPO;
import com.infra.micro.oss.domain.db.entity.FileInfoPO;
import com.infra.micro.oss.domain.repository.BizInfoRepository;
import com.infra.micro.oss.domain.repository.FileInfoRepository;
import com.infra.micro.oss.domain.service.BizInfoService;
import com.infra.micro.oss.model.req.QueryBizInfoReq;
import com.infra.micro.oss.model.vo.BizFileVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BizInfoServiceImpl extends BaseFileService implements BizInfoService {
    @Resource
    private BizInfoRepository bizInfoRepository;
    @Resource
    private FileInfoRepository fileInfoRepository;

    @Override
    public Response<BizFileVO> queryByBizId(Long bizId) {
        BizInfoPO bizInfoPO = bizInfoRepository.queryByBizId(bizId);
        if (bizInfoPO == null) {
            return Response.error("bizId无效，文件未找到!");
        }

        FileInfoPO fileInfoPO = fileInfoRepository.queryByFileId(bizInfoPO.getFileId());
        return Response.success(buildBizFileVO(bizInfoPO, fileInfoPO), "查询成功");
    }

    @Override
    public Response<List<BizFileVO>> queryByBizIds(List<Long> bizIds) {
        return Response.success(bizInfoRepository.queryByBizIds(bizIds), "查询成功");
    }

    @Override
    public Response<PageEx<BizFileVO, QueryBizInfoReq>> queryByPage(QueryBizInfoReq req) {
        PageInfo<BizFileVO> pageInfo = PageHelper.startPage(req.getPageIndex(), req.getPageSize(), BizUtils.buildOrderByClause(req.getSortField(), req.getSortType()))
                .doSelectPageInfo(() -> bizInfoRepository.queryByCond(req));

        return Response.success(PageEx.builder(pageInfo, req), "查询成功");
    }

    public Response<Boolean> deleteByBizId(Long bizId) {
        int ret = bizInfoRepository.deleteByBizId(bizId);
        return Response.success(true, "删除成功，影响行数:" + ret);
    }

    public Response<Boolean> deleteByBizIds(List<Long> bizIds) {
        int ret = bizInfoRepository.deleteByBizIds(bizIds);
        return Response.success(true, "删除成功，影响行数:" + ret);
    }

    public Response<Boolean> deleteByAppId(String appId) {
        int ret = bizInfoRepository.deleteByAppId(appId);
        return Response.success(true, "删除成功，影响行数:" + ret);
    }

}
